<?php
// +----------------------------------------------------------------------
// | 简易CMS
// +----------------------------------------------------------------------
// | Copyright (C) 2010 Hoping Software Studio.
// +----------------------------------------------------------------------
// | Version $Id$
// +----------------------------------------------------------------------
namespace app\home\controller;

/**
 * @package 简易CMS
 * @category 固定内容前台控制模板
 */
class Article extends HomeController {
    function Index() {
        /* 分类信息 */
        $model = model('ArticleTitle');
        $total = I('g.total');
        if (!$total) {
            $total = $model->count();
        }
        $statics = S('statics');
        if (!$statics) {
            $day = NOW_TIME - 24 * 3600;
            $week = NOW_TIME - 7 * 24 * 3600;
            $statics = array(
                'day'  => $model->where('update_time>=' . $day)->count(),
                'week' => $model->where('update_time>=' . $week)->count()
            );
            S('statics', $statics, 30 * 60);
        }

        $page = new \CMS\Page($total, 10, array('total' => $total));
        $multi = $page->show();
        $this->assign('multi', $multi);
        $this->assign('page', $page);
        $this->assign('statics', $statics);
        $this->assign('total', $total);
        return $this->fetch();
    }

    /**
     * 前台文章浏览模块
     */
    function View() {
        $aid = I('id/d', 0);
        $page = max(1, I(C('VAR_PAGE', null, 'p'), 1, '/d'));

        $model = D('ArticleTitle');
        $cates = S('categories');
        $customfields = S('customfields');
        $tophtml = $bottomhtml = '';

        if (!$aid) {
            return $this->error('对不起，您没有指定要查看的新闻！');
        }
        $article = $model->detail($aid, $page);
        if ($article === false) {
            return $this->error($model->getError());
        }
        if (!$article) {
            return $this->error('对不起，您指定要查看的新闻不存在！');
        }
        $catid = $article['category_id'];

        $this->assign('catid', $article['category_id']);
        if (!IS_ROBOT && !cookie('view_article_' . $aid)) {
            $model->setinc('viewnum');
            cookie('view_article_' . $aid, 1, 1800);
        }

        if (empty($article) || ($article ['status'] === 0 && $article ['uid'] != $this->user['uid'])) {
            $this->error("指定的内容不存在或者您无权查看!");
        }

        $model = \think\Db::name('Tags');
        $tags = $model->alias('a')
            ->join('__TAGSLIST__ AS b', 'b.tagid=a.tagid', 'LEFT')
            ->where("a.itemid='$aid' AND a.tagtype='portal'")
            ->select();
        $article ['tags'] = $tags;

        $article ['custom'] = array(
            'name'  => '',
            'key'   => array(),
            'value' => array()
        );
        if (!empty($article ['customfieldid'])) {
            $article ['custom'] ['value'] = unserialize($article ['customfieldtext']);
            if ($article ['custom'] ['value']) {
                $fields = $customfields [$article ['customfieldid']];
                $article ['custom'] ['name'] = $fields ['name'];
                $article ['custom'] ['key'] = $fields ['customfieldtext'];
                foreach ($article ['custom'] ['value'] as $key => $value) {
                    if ($value) {
                        $cf = $article ['custom'] ['key'] [$key];
                        ProcessCustomField($cf, $value, $tophtml, $bottomhtml);
                    }
                }
                if ($tophtml)
                    $tophtml = '<table class="customfields">' . $tophtml . '</table>';
                if ($bottomhtml)
                    $bottomhtml = '<table class="customfields">' . $bottomhtml . '</table>';
            }
        }
        if ($cat ['upid']) {
            $_G ['topcatid'] = $cat ['upid'];
        } else {
            $_G ['topcatid'] = $_G ['catid'];
        }

        $page = max(1, intval(I('g.page')));
        if ($page > 1 && $page > $article['contents']) {
            $this->error('对不起，您指定的页面不存在！', 1, U('Article/view', array('id' => $aid)));
        }
        $article['content'] = $tophtml . $article ['content'] . $bottomhtml;

        //$multi = multi($article ['contents'], 1, $page, U('Article/view', array('id'=>$aid)));
        $this->assign('multi', $multi);
        $upDriver = C('upload.driver');
        $upConfig = C('upload.' . $upDriver . '_config');
        $upurl = $upConfig['urlpre'];

        /**
         * 读取相关文章，这里来说，如果是自动采集过来的文章，通常是不会手动去设置相关文章的，所以就以KID为主要的判断依据
         */
        $article ['related'] = array();
        $model = D('ArticleTitle');
        if ($article ['kid']) {
            $kid = $article ['kid'];
            $where = "id!='$aid' AND kid='$kid' AND pic!=''";
            $order = "id DESC";
            $article ['related'] = $model->where($where)->order($order)->limit(0, 8)->select();
        }
        //没有相关文章则取该分类下最新发布的文章
        if (!$article['related'] && !$article['kid']) {
            $where = "id!='$aid' AND category_id='$catid' AND pic!=''";
            $order = "id DESC";
            $article ['related'] = $model->where($where)->order($order)->limit(0, 8)->select();
        }
        if ($article['related']) {
            foreach ($article['related'] as &$v) {
                $v['pic'] = $upurl . '/article/' . $v['pic'];
            }
        }

        /**
         * 读取图片
         */
        $aimgs = array();
        $rows = \think\Db::name('Attachment')->where("aid='$aid' AND isimage='1'")->select();
        foreach ((array) $rows as $value) {
            if ($value ['thumb']) {
                $value ['thumb'] = $value ['attachment'] . '.thumb.jpg';
            } else {
                $value ['thumb'] = $value ['attachment'];
            }
            $value ['thumb'] = $upurl . '/article/' . $value ['thumb'];
            $value ['pic'] = $upurl . '/article/' . $value ['attachment'];
            $basename = basename($value ['pic']);
            if (!strpos($article ['content'], $basename))
                $aimgs [] = $value;
        }
        $this->assign('aimgs', $aimgs);

        // 给投票做个HASH值，避免恶意投票
        $hash = md5($article ['uid'] . "\t" . $article['update_time']);
        $this->assign('hash', $hash);

        //下一篇和下一篇
        $sql = "(SELECT id,title,shorttitle FROM __ARTICLE_TITLE__ WHERE id < $aid AND category_id = $catid ORDER BY id DESC LIMIT 0,1)
				UNION ALL
				(SELECT id,title,shorttitle FROM __ARTICLE_TITLE__ WHERE id > $aid AND category_id = $catid ORDER BY id ASC LIMIT 0,1)";
        //这里需要自动去处理一下表名的前缀！
        $sql = \think\Db::connect()->parseSqlTable($sql);
        $result = \think\Db::query($sql);
        $next = $prev = array();
        if ($result) {
            if (count($result) == 1) {
                if ($result[0]['id'] < $aid) {
                    $prev = $result[0];
                } else {
                    $next = $result[0];
                }
            } else {
                $prev = $result[0];
                $next = $result[1];
            }
        }
        $navtitle = $article ['title'] . ($page > 1 ? " ( $page )" : '') . ' - ' . $cat ['catname'];
        $metakeywords = $article ['keywords'] ? $article ['keywords'] : $article ['title'];
        $metadescription = $article ['summary'] ? $article ['summary'] : $article ['title'];
        $tpl = $cat ['contenttplname'] ? $cat ['contenttplname'] : 'article/view';
        $a = array('article', 'navtitle', 'metakeywords', 'metadescription', 'prev', 'next', 'content', 'cat');
        foreach ($a as $k) {
            $this->assign($k, $$k);
        }
        return $this->fetch($tpl);
    }

    /**
     * 分类内容列表
     *
     * @global array $_G 系统全局变量
     */
    function Lists() {
        $catid = I('id/d');
        $category = I('category/s', '', 'trim');
        if (empty($catid) && empty($category)) {
            $this->error("您没有指定要查看的分类!");
        }
        $this->assign('catid', $catid);
        $m = D('Category');
        $map = array(
            'status' => 1
        );
        if ($catid) {
            $map['id'] = $catid;
        } else {
            $map['name'] = $category;
        }
        $cat = $m->where($map)->find();
        $this->assign('category', $cat);
        if (empty($cat)) {
            $this->error("对不起，您指定的分类不存在!");
        }
        $total = I('total/d');
        if (!$total) {
            $total = D('ArticleTitle')->listCount($cat['id']);
        }
        $vars = array('total' => $total);
        if ($catid) {
            $vars['id'] = $cat['id'];
        } else {
            $vars['category'] = $cat['name'];
        }
        $page = new \CMS\Page($total, 10, $vars);
        $multi = $page->show();
        $this->assign('multi', $multi);

        return $this->fetch('article/index');
    }

    function Attachment() {
        global $_G;
        $operation = I('r.op');

        $id = empty($_GET ['id']) ? 0 : intval($_GET ['id']);
        $aid = empty($_GET ['aid']) ? '' : intval($_GET ['aid']);
        $model = D('Attachment');
        $attach = $model->find($id);
        if (empty($attach)) {
            $this->error('对不起，您指定的文件不存在！');
        }

        if ($operation == 'delete') {
            if (!$_G ['group'] ['allowmanagearticle'] && $_G ['uid'] != $attach ['uid']) {
                $this->error("对不起，您无权删除此文件！");
            }
            if ($aid) {
                DB::query("UPDATE #__article_title SET pic = '' WHERE aid='$aid'", 'UNBUFFERED');
            }
            $model->delete($id);
            pic_delete($attach ['attachment'], $attach ['thumb'], 0);
            $this->success("指定的文件已经删除!");
        } else {
            $filename = A_DIR . $attach ['attachment'];
            if (!is_readable($filename)) {
                $this->error('您指定的文件无法被删除！');
            }

            $readmod = 2; // read local file's function: 1=fread 2=readfile
            // 3=fpassthru 4=fpassthru+multiple
            $range = 0;
            if ($readmod == 4 && !empty($_SERVER ['HTTP_RANGE'])) {
                list ( $range ) = explode('-', (str_replace('bytes=', '', $_SERVER ['HTTP_RANGE'])));
            }

            $filesize = $attach ['filesize'];
            $attach ['filename'] = '"' . (strtolower(CHARSET) == 'utf-8' && strexists($_SERVER ['HTTP_USER_AGENT'], 'MSIE') ? urlencode($attach ['filename']) : $attach ['filename']) . '"';

            CMS\Misc::header('Date: ' . gmdate('D, d M Y H:i:s', $attach ['update_time']) . ' GMT');
            CMS\Misc::header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $attach ['update_time']) . ' GMT');
            CMS\Misc::header('Content-Encoding: none');
            CMS\Misc::header('Content-Disposition: attachment; filename=' . $attach ['filename']);
            CMS\Misc::header('Content-Type: ' . $attach ['filetype']);
            CMS\Misc::header('Content-Length: ' . $filesize);

            if ($readmod == 4) {
                CMS\Misc::header('Accept-Ranges: bytes');
                if (!empty($_SERVER ['HTTP_RANGE'])) {
                    $rangesize = ($filesize - $range) > 0 ? ($filesize - $range) : 0;
                    CMS\Misc::header('Content-Length: ' . $rangesize);
                    CMS\Misc::header('HTTP/1.1 206 Partial Content');
                    CMS\Misc::header('Content-Range: bytes=' . $range . '-' . ($filesize - 1) . '/' . ($filesize));
                }
            }

            getlocalfile($filename, $readmod, $range);
        }
    }

}
